# -*- coding: utf-8 -*-
import json
import os
import sys
import time
import urllib.parse
from paddleocr import PaddleOCR
import base64
t = time.time()
# 初始化OCR
runpath = os.path.abspath(".")
ocr = PaddleOCR(
    det_model_dir=runpath + "/det/",  # 检测模型目录
    det_max_side_len=960,  # 图片长边的最大尺寸,超出缩放,正常游戏截图都比较小使用默认基本都可以
    det_db_thresh=0.2,  # 检测模型输出预测图的二值化阈值                        影响识别关键0.1-1之间自己调整
    det_db_box_thresh=0.3,  # 检测模型输出框的阈值, 低于此值的预测框会被丢弃          影响识别关键0.1-1之间自己调整
    # 检测模型输出框扩大的比例                              影响识别关键0.1-10之间自己调整 游戏正常在0.3-2之间
    det_db_unclip_ratio=2,
    rec_model_dir=runpath + '/rec/',  # 识别模型目录
    rec_char_dict_path=runpath + '/rec/dict.txt',  # 识别字典文件
    use_space_char=True,  # 是否识别空格
    max_text_length=50,  # 识别的最大文字长度
    cls_model_dir=runpath + '/cls/',  # 分类模型目录 正常用不到
    use_gpu=False,  # 使用GPU
    lang="ch",  # 模型语言类型,目前支持 中文(ch)、英文(en)及数字  ch=中文+数字+英文
    det=True,  # 使用启动检测
    rec=True,  # 是否启动识别
    cls=False,  # 是否启动分类
)


def myocr(img):
    try:
        result = ocr.ocr(img, det=True, cls=False)
        # file = open("result", "w")
        # file.write(result)
        # file.close()
        retrec = {}
        text = ""
        index = 1
        text_rec = ''
        for k, v in result:
            # text = text + v[0]   # 识别到的文字
            text = v[0]
            text_rec = text_rec + v[0]
            score = '{:.3f}'.format(v[1])  # 识别准确率 保留小数点后三位
            loc = str(k)
            # 记录识别框坐标位置
            topleft = str(k[0])
            topright = str(k[1])
            botright = str(k[2])
            botleft = str(k[3])
            # top = str(int(k[0][0])) + "," + str(int(k[0][1]))  # 识别文本相对图片顶点坐标
            # mid = str(int(k[1][0])) + "," + str(int(k[1][1]))  # 识别文本相对图片顶点坐标
            # bot = str(int(k[2][0])) + "," + str(int(k[2][1]))  # 识别文本相对图片下边坐标
            # retrec[text] = {"top": top, "mid":mid, "bot": bot, "score": score}
            retrec[str(index)] = {
                "text": text,
                "score": score,
                "topleft": topleft,
                "topright": topright,
                "botright": botright,
                "botleft": botleft
            }
            index += 1
            # retrec[text] = {'score': score}
        json.dumps(retrec, indent=4, ensure_ascii=False)
        retrec = str(retrec)
        retrec = retrec.replace("'", "\"")
        file = open("result.json", "w")  # 写入json文件内容
        file.write(retrec)
        file.close()
        return text_rec
    finally:
        pass


def text_ocr(src):
    # try:
    img = open(src, mode="rb")
    base64_data = base64.b64encode(img.read())  # 文件用base64编码
    s = base64_data.decode()
    img = urllib.parse.unquote(s)  # 转换成为url编码
    if len(img) == 0 or len(img) > 500000:
        return "拒绝处理，因为img数据过大或缺失"
    date_string = time.strftime(
        "%Y-%m-%d-%H-%M-%S")
    name =date_string + ".jpg"
    # name = str(random.randint(1, 10)) + ".jpg"
    file = open(name, "wb")
    imgb = base64.b64decode(img)  # base64解码
    file.write(imgb)
    file.close()
    txt = myocr(name)
    os.remove(name)
    # loc = handle(name)
    print(txt)


#
# except:
#     return "未转编码base64->url"
if __name__ == '__main__':
    text_ocr(sys.argv[1])
